# -*- coding:utf-8 -*-
import jwt
import datetime
from django.conf import settings
from django.contrib.auth import get_user_model, authenticate
from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed, ValidationError
from rest_framework import exceptions
from django.contrib.auth import get_user_model


class JwtTokenAuthentication(BaseAuthentication):
    keyword = 'token'

    def authenticate(self, request):
        try:
            token = request.headers["Authorization"].split(' ')[1]
            salt = settings.SECRET_KEY
            payload = jwt.decode(token, salt, True)
        except jwt.exceptions.ExpiredSignatureError:
            raise AuthenticationFailed("token已失效")
        except jwt.DecodeError:
            raise AuthenticationFailed("token认证失败")
        except jwt.InvalidTokenError:
            raise AuthenticationFailed("非法的token")
        except KeyError:
            raise AuthenticationFailed("没有传token")

        return self.authenticate_credentials(payload, token)

    def authenticate_credentials(self, payload, token):

        model = get_user_model()

        user = model.objects.filter(username=payload["username"]).filter(id=payload["user_id"]).first()
        if user is None:
            raise exceptions.AuthenticationFailed("未查询到该用户")

        if not user.is_active:
            raise exceptions.AuthenticationFailed("该用户已被删除")
        return (user, token)

    def authenticate_header(self, request):
        return self.keyword


def JwtToken_create(obj):
    # 加盐
    salt = settings.SECRET_KEY

    # 头部信息
    headers = {
        'typ': 'jwt',
        'alg': 'HS256'
    }

    #
    payload = {
        'user_id': obj.id,
        'username': obj.username,
        'exp': datetime.datetime.utcnow() + datetime.timedelta(seconds=settings.JWT_TOKEN_TIMEOUT)  # 超时时间
    }

    token = jwt.encode(payload=payload, key=salt, algorithm='HS256', headers=headers)
    return token
